from django.shortcuts import render, HttpResponse, redirect
from app01 import models


# Create your views here.


def login(request):
    return render(request, 'login.html')


def publisher_list(request):
    all_publisher = models.Publisher.objects.all()
    for i in all_publisher:
        print(i)
        print(i.name)
        print(i.id)
    return render(request, 'publisher_list.html', {'all_publisher': all_publisher})


def publisher_add(request):
    if request.method == 'POST':
        pub_name = request.POST.get('pub_name')
        models.Publisher.objects.create(name=pub_name)
        return redirect('/publisher_list/')

    return render(request, 'publisher_add.html')


def publisher_del(request):
    pk = request.GET.get("pk")
    #models.Publisher.objects.get(pk=pk).delete()
    models.Publisher.objects.filter(pk=pk).delete()

    return redirect('/publisher_list/')


def publisher_edit(request):
    pk = request.GET.get('pk')
    pub_obj = models.Publisher.objects.get(pk=pk)
    if request.GET == "GET":
        return render(request,'publisher_edit.html',{'pub_obj':pub_obj})
    else:

        pub_name = request.POST.get("pub_name")
        pub_obj.name = pub_name
        pub_obj.save()
    return redirect('/publisher_list/')


def book_lsit(request):
    all_books = models.Book.objects.all()
    #for book in all_books:
        # print(book)
        # print(book.pk)
        # print(book.name)
        # print(book.publisher,book.publisher.name,book.publisher.pk)
        # print(book.publisher_id)#实际的字段
    return render(request,'book_list.html',{"all_books":all_books})
